<?php
/**
 * @author shutyuka@gmail.com
 * @modified 2011-02-20
 */
class Devices{
	
	static public $FLAG_INACTIVE = 0;
	
	static public $FLAG_UNACTIVE = 10;
	
	static public $TABLE_NAME="devices";

	static public function Create($device) {
		$device['create_time'] = time();
		$device['id'] = DB::Insert(self::$TABLE_NAME, $device);
		
		return $device['id'];
	}
	
	static public function Update($device) {
		Table::UpdateCache(self::$TABLE_NAME, $device['id'], $device);
		
		return ;
	}
	
	static public function GetAll(){
		$oc = array( 
			'activity' => self::$FLAG_INACTIVE
			);
		$allShops = DB::LimitQuery(self::$TABLE_NAME, array(
				'condition' => $oc,
				'order' => 'ORDER BY id ASC'
				));
		return $allShops;
	}
	
	static public function GetAllByShopId($shopId){
		$oc = array( 
			'activity' => self::$FLAG_INACTIVE,
			'shop_id' => $shopId
			);
		$allShops = DB::LimitQuery(self::$TABLE_NAME, array(
				'condition' => $oc,
				'order' => 'ORDER BY id ASC'
				));
		return $allShops;
	}
	
	static public function GetDeviceCountForService($shopId, $serviceId){
		if( $serviceId < 1 ){
			$sql = "select sum(`device_count`) as count from devices where devices.shop_id=$shopId";
		}else{
			$sql = "select sum(`device_count`) as count from devices, device_use where devices.shop_id=$shopId and device_use.service_id=$serviceId and device_use.device_id=devices.id;" ;
		}
		//Logs::setLog(" device log is || $sql  ||  ");
		return DB::GetQueryResult($sql, false);
		
	}
	
	static public function GetById($id) {
		if (!$id) return array();
		return DB::GetTableRow(self::$TABLE_NAME, array('id' => $id));
	}

	static public function SetDeviceUnactive($deviceId) {
		if (!$deviceId) 
			return array();
		Table::UpdateCache(self::$TABLE_NAME, $deviceId, array(
			'activity' => self::$FLAG_UNACTIVE)
		);
		return ;
	}
	
	
	static public function SetDeviceInActive($deviceId) {
		if (!$deviceId) 
			return array();
		Table::UpdateCache(self::$TABLE_NAME, $deviceId, array(
			'activity' => self::$FLAG_INACTIVE)
		);
		return ;
	}
	
	static public function DeleteById($id, $opId){
				
		$sql = "delete from ".self::$TABLE_NAME." where id=$id" ;
		DeviceUse::DeleteById($id);
		//Logs::setLog("new sql is || $sql ||");
		return DB::GetQueryResult($sql, false);
	}
	
}
